import { createRouter, createWebHashHistory } from "vue-router";
import app from "@/main";
import adminRoutes from "./admin";
import mainRoutes from "./main";

import mainStore from "@/stores/main";
import { message } from "ant-design-vue";

import Nprogress from "nprogress";
import "nprogress/nprogress.css";
Nprogress.configure({ showSpinner: false,  speed: 500 });

const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes: [
        {
            name: "home",
            path: "/",
            component: () => import("@/pages/Index.vue"),
            redirect: "/websites",
            children: [
                ...adminRoutes,
                ...mainRoutes,
            ]
        },
        {
            path: "/login",
            meta: { title: "登录" },
            component: () => import("@/pages/Login.vue")
        },
        {
            path: "/blank-space",
            component: () => import("@/pages/BlankSpace.vue")
        },
        {
            path: "/:catchAll(.*)",
            component: () => import("@/pages/NotFound.vue")
        }
    ]
});

router.beforeEach((to) => {
    Nprogress.start();
    const { title } = to.meta;
    if (title) {
        document.title = <string>title;
    }
    const $store = mainStore();
    if (to.meta.isAdmin) {
        if ($store.userInfo && $store.userInfo.level === 1) {
            return true;
        }
        return "/404";
    }
    if (to.path !== "/login" && to.name !== "not-found") {
        
    }
    return true;
});
router.afterEach(() => {
    removeLoading();
    // 路由加载完成!
    Nprogress.done();
    return true;
});
router.onError(()=>{
    removeLoading();
    Nprogress.remove()
})

const removeLoading = () => {
    document.querySelector("#loading-box")?.remove();
};

export default router;
